package com.yuji.aacar.core.mvvm.appbase;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.permission.PermissionUtils;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.core.mvvm.apptask.TaskManager;
import com.yuji.aacar.core.mvvm.apptask.TaskToken;
import com.yuji.aacar.core.mvvm.apptask.ViewModelManager;
import com.yuji.aacar.widgets.loading.CustomDialog;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <li>Package:com.ttp.core.mvvm.appbase</li>
 * <li>Author: lining</li>
 * <li>Date: 2017/2/14</li>
 * <li>Description: <br>所有Activity基类</br></li>
 */

public abstract class CoreBaseActivity extends Activity implements CoreBaseController {

    /**
     * 基类ViewModel对象
     */
    public CoreBaseViewModel coreBaseViewModel;

    /**
     * 请求的viewModelId
     */
    private String viewModelId;


    /**
     * coreProgressDialog
     */
//    public static Dialog coreProgressDialog;
//    public static CoreProgressDialog coreProgressDialog;
    public CustomDialog coreProgressDialog;


    public LayoutInflater mInflater;

    /**
     * 需要适配的当前View
     */
    public View mView;
    /**
     * mToast
     */
    private Toast mToast;

    public static Handler coreHandler;

    /**
     * 双击退出app
     */
    private static Boolean isExit = false;
    private boolean isHome;

    /**
     * 接收请求params的对象
     */
    public HashMap<String, Object> requestParams;

    public Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mInflater = LayoutInflater.from(this);
//        coreProgressDialog = new CoreProgressDialog(this);
        //        if (null == coreProgressDialog){
        //            coreProgressDialog = new CoreProgressDialog(this);
        ////            coreProgressDialog.show();
        //        }
        if (null == coreHandler) {
            coreHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    LogUtil.e("--handleMessage--", msg.what);
                    switch (msg.what) {
                        case 0:
                            dismissLoadingDialog();
                            break;
                        case 1:
                            showLoadingDialog();
                            break;
                    }
                }
            };
        }

        //        requestTokens = new ArrayList<TaskToken>();
        Intent intent = getIntent();
        if (null != intent.getExtras()) {
            viewModelId = intent.getExtras()
                    .getString(AppRoute.ACTIVITY_TOKEN_KEY);
        }
        CoreEventCenter.register(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.e("--onStart--coreBaseViewModel == null --", coreBaseViewModel == null ? "是空的" : coreBaseViewModel.getClass().getName());
        LogUtil.e("--onStart--coreBaseViewModel == viewModelId --", viewModelId == null ? "没有viewModelId" : viewModelId);
        if (null == coreBaseViewModel) {
            coreBaseViewModel = ViewModelManager.getInstance().viewModelForKey(
                    viewModelId);
            if (null != coreBaseViewModel) {
                LogUtil.e("--onStart--根据viewModelId获得到的coreBaseViewModel--", "[CoreBaseActivity]当前的---coreBaseViewModel---" + coreBaseViewModel.getClass());
                LogUtil.e("--onStart--this--", this.getClass().getSimpleName());
                LogUtil.e("--onStart--this--coreBaseViewModel--", coreBaseViewModel);
                coreBaseViewModel.setActivity(this);
                alreadyBindBaseViewModel();
                if (coreBaseViewModel.getResponse() != null) {
                    if (coreBaseViewModel.isDataReady.get()
                            && !coreBaseViewModel.isRefreshed.get()) {
                        requestSuccess(coreBaseViewModel.getResponse());
                    } else if (coreBaseViewModel.isFailed.get()) {
                        LogUtil.e("activity", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel.isFailed");
                        coreBaseViewModel
                                .requestFailed(coreBaseViewModel.getResponse());
                    } else {
                        coreBaseViewModel.requestFailed(coreBaseViewModel.getResponse());
                    }
                } else {
                    LogUtil.e("activity", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel.getResponse() == null");
                }
            } else {
                LogUtil.e("--onStart--根据viewModelId获得到的coreBaseViewModel--", "是空的，需要重新生成一个model");
                LogUtil.e("activity", this.getClass().getSimpleName() + "[onStart][baseviewmodel viewModelId]:" + viewModelId + " is null");
                coreBaseViewModel = ViewModelManager.getInstance().newViewModel(this.getClass().getName());
                coreBaseViewModel.showProgressBar = false;
                coreBaseViewModel.setActivity(this);
                viewModelId = coreBaseViewModel.getViewModelId();
                alreadyBindBaseViewModel();
                LogUtil.d("---corebaseactivity---", "create new viewModel:[" + viewModelId + "]");
            }
        } else {
            LogUtil.e("---corebaseactivity---", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel is NOT null (should be null)");
            LogUtil.e("---corebaseactivity---", this.getClass().getSimpleName() + "[onStart][coreBaseViewModel]: is Not Null!");
            LogUtil.e("---corebaseactivity---", this.getClass().getSimpleName() + "[onStart][coreBaseViewModel]:" + coreBaseViewModel.getClass());
        }
    }

    @Override
    public void onBackPressed() {
        LogUtil.e("--onBackPressed--", coreProgressDialog);
        cancelToast();
        dismissLoadingDialog();
        super.onBackPressed();
        destoryViewModel();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        LogUtil.e("--onKeyDown--", coreProgressDialog);
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dismissLoadingDialog();
        }
        if (isHome && (keyCode == KeyEvent.KEYCODE_BACK)) {
            exitBy2Click();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoadingDialog();
        destoryViewModel();
        CoreEventCenter.unregister(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (coreBaseViewModel != null) {
            coreBaseViewModel.isRefreshed.set(false);
        }
    }

    /**
     * activity已经绑定了viewmodel，可以直接调用baseviewmodel获取viewmodel
     */
    public void alreadyBindBaseViewModel() {
        LogUtil.e("--alreadyBindBaseViewModel--coreBaseViewModel.getTaskToken()--", coreBaseViewModel.getTaskToken() == null ? "没有请求token" : coreBaseViewModel.getTaskToken());
    }

    /**
     * 网络请求成功刷新界面
     */
    @Override
    public void requestSuccess(CoreServiceResponse response) {
        coreBaseViewModel.isRefreshed.set(true);
        dismissLoadingDialog();
    }

    @Override
    public void requestFailed(CoreServiceResponse response) {
        dismissLoadingDialog();
    }

    public void destoryViewModel() {
        LogUtil.e(this.getClass().getSimpleName(), " destoryViewModel() is called!!!");
        if (coreBaseViewModel != null) {
            LogUtil.e("--destoryViewModel--", coreBaseViewModel);
            LogUtil.e("--destoryViewModel--", coreBaseViewModel.getTaskToken());
            TaskManager.getInstance().cancelTask(coreBaseViewModel.getTaskToken());
        }
        ViewModelManager.getInstance().destoryViewModel(viewModelId);
    }

    public String getViewModelId() {
        return viewModelId;
    }

    @Override
    public CoreBaseViewModel getViewModel() {
        return coreBaseViewModel;
    }

    @Override
    public void setViewModel(CoreBaseViewModel viewModel) {
        coreBaseViewModel = viewModel;
    }

    //    public abstract void startProgressDialog(boolean cancle);


    public void showLoadingDialog() {
        if (coreProgressDialog == null) {
            coreProgressDialog = new CustomDialog(mContext,"加载中...");
//            coreProgressDialog.setOnDismissListener(this);
        }
        if (!coreProgressDialog.isShowing()) {
            coreProgressDialog.show();
        }
    }

    public void dismissLoadingDialog() {
        if (coreProgressDialog != null && coreProgressDialog.isShowing()) {
            coreProgressDialog.dismiss();
        }
    }


//    /**
//     * 加载progressView
//     */
//    public void showProgress() {
//        if (coreProgressDialog != null) {
//            if (!coreProgressDialog.isShowing()) {
//                coreProgressDialog.show();
//            }
//        }
//    }
//
//    /**
//     * 取消ProgressView
//     */
//    public void dismissProgress() {
//        if (coreProgressDialog != null) {
//            if (coreProgressDialog.isShowing()) {
////                coreProgressDialog.applyDismiss();
//                coreProgressDialog.dismiss();
//            }
//        }
//    }

    public void showToast(String text) {
        this.showToast(text, Toast.LENGTH_SHORT);
    }

    public void showToast(String text, int duration) {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
        mToast = Toast.makeText(this, text, duration);
        mToast.setGravity(Gravity.CENTER, 0, 0);
        mToast.show();
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

    /**
     * 运行时申请权限，当前targetSdkVersion是22，无需调用这个方法
     * @param requestCode 详见PermissionUtils中的Code码
     */
    protected void requestPermission(int requestCode) {
        PermissionUtils.requestPermission(this, requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 双击退出应用
     */
    public void setHomePageAndExitApp(boolean b) {
        isHome = b;
    }

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出

                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            if (tExit != null) {
                tExit.cancel();
            }
            exit();
        }
    }

    private void exit() {
        finish();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Subscribe
    public void onEventBusMessage(CoreEventBusMessage message) {
        handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(CoreEventCenter.BUSSINESS_SERVICE_ERROR))) {
            TaskToken token = new TaskToken();
            token.methodName = message.getMethodName();
            token.requestCode = message.getRequestCode();
            CoreServiceResponse response = new CoreServiceResponse();
            response.setRequestCode(message.getRequestCode());
            response.setTokenObj(token);
            response.setMessage(message.getMessage());
            response.setResultCode(CoreEventCenter.BUSSINESS_SERVICE_ERROR);
            requestFailed(response);
        } else if (message.getMessageCode().contentEquals(String.valueOf(CoreEventCenter.NETWOR_NOT_CONNECT))) {
            TaskToken token = new TaskToken();
            token.methodName = message.getMethodName();
            token.requestCode = message.getRequestCode();
            CoreServiceResponse response = new CoreServiceResponse();
            response.setRequestCode(message.getRequestCode());
            response.setTokenObj(token);
            response.setMessage(message.getMessage());
            response.setResultCode(CoreEventCenter.NETWOR_NOT_CONNECT);
            requestFailed(response);
        }
    }

    public void handleMessage(CoreEventBusMessage message) {
        dismissLoadingDialog();
    }

    /*********
     * 网络请求
     * @param method
     */
    public void doTask(String method) {
        showLoadingDialog();
        TaskToken token = TaskManager.getInstance().doTask(coreBaseViewModel, method, requestParams);
        LogUtil.e("doTask get taskToken",token);
    }

    /*********
     * 网络请求
     * @param method
     * @param params
     */
    public void doTask(String method, HashMap<String, Object> params) {
        TaskManager.getInstance().doTask(coreBaseViewModel, method, params);
    }

    /**
     * 取消一个网络请求,需要传入dotask时候返回的唯一令牌
     *
     * @param token 线程对象
     */
    public void cancelTask(TaskToken token) {
        TaskManager.getInstance().cancelTask(token);
    }

}
